package com.dragon.modules.yuegou.client.ali.client.impl;

import com.dragon.modules.yuegou.client.ali.client.AuthClient;
import com.dragon.modules.yuegou.client.ali.response.UserInfo;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.io.IOException;
import java.io.UncheckedIOException;

@Service
public class AuthClientImpl implements AuthClient {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    private WebClient client = WebClient.create("https://aliauth.oojoyoo.com");
    private ObjectMapper objectMapper;

    public AuthClientImpl(){
        objectMapper = new ObjectMapper();
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    @Override
    public UserInfo userinfo(String appid, String token, String code) {
        String text = client.get()
                .uri(b -> b.path("/userinfo")
                        .queryParam("token", token)
                        .queryParam("appid", appid)
                        .queryParam("code", code)
                        .build())
                .accept(MediaType.APPLICATION_JSON_UTF8)
                .exchange()
                .flatMap(res -> res.bodyToMono(String.class))
                .block();
        logger.debug("userinfo : {}", text);
        try {
            return objectMapper.readerFor(UserInfo.class).readValue(text);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}
